<template>
  <tr><th v-for="column in columns" :key="column.label">{{column.label}}
    <template v-if="column.sortable">
      <svg-icon class="sort" :icon-class="icon" @click="sort(column)"></svg-icon>
    </template>
  </th></tr>
</template>

<script>
export default {
  name: "KTableHeader",
  props: ['columns', 'data'],
  data() {
    return {icon:'sort'}
  },
  methods: {
    compareUp(data, propertyName) {
// 升序排序
      if (typeof data[0][propertyName] != 'number') {
// 属性值为⾮数字
        return function (object1, object2) {
          var value1 = object1[propertyName]
          var value2 = object2[propertyName]
          return value1.localeCompare(value2)
        }
      } else {
        return function (object1, object2) {
// 属性值为数字
          var value1 = object1[propertyName]
          var value2 = object2[propertyName]
          return value1 - value2
        }
      }
    },
    compareDown(data, propertyName) {
// 降序排序
      if (typeof data[0][propertyName] != 'number') {
// 属性值为⾮数字
        return function (object1, object2) {
          var value1 = object1[propertyName]
          var value2 = object2[propertyName]
          return value2.localeCompare(value1)
        }
      } else {
        return function (object1, object2) {
// 属性值为数字
          var value1 = object1[propertyName]
          var value2 = object2[propertyName]
          return value2 - value1
        }
      }
    },
    descending(column) {
      this.data.sort(this.compareDown(this.data, column.prop))
    },
    ascending(column) {
      this.data.sort(this.compareUp(this.data, column.prop))
    },
    sort(column) {
      this.flag = !this.flag;
      !this.flag ? this.ascending(column) : this.descending(column);
      this.icon = `sort${this.flag ? 2 : 1}`
    }
  }}
</script>

<style scoped>
.sort {
  cursor: pointer;
}
</style>
